import json

from common.api import http_result
from user_module.models import GlobalData
from user_module.rpc import user_pb2_grpc
from user_module.models import MenuInfo


class MenuHandler(user_pb2_grpc.MenuServicer):

    def do_save_cur_menu(self, param, session):
        menu = param.get('menu')
        sub_menu = param.get('sub_menu')
        info = json.dumps({
            'menu': menu,
            'sub_menu': sub_menu,
        }, ensure_ascii=False)
        key = '_user_' + session['user_phone']
        GlobalData.delete().where(GlobalData.key == key).execute()

        data = GlobalData()
        data.key = key
        data.value = info
        data.save()
        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_query(self, param, session):
        result = []
        menus = MenuInfo.select().order_by(MenuInfo.sorted_index).offset(0).limit(15)
        for m in menus:
            tmp = {
                'id': m.id,
                'menu': m.menu,
                'icon': m.icon,
                'url': m.url,
                'sorted_index': m.sorted_index,
            }
            result.append(tmp)
        return self.resp(1, http_result.RESULT_SUCCESS, result)

    def do_update(self, param, session):
        mid = param.get('id')
        if mid:
            menu = MenuInfo.get_by_id(mid)
        else:
            menu = MenuInfo()
        menu.menu = param.get('menu')
        menu.url = param.get('url')
        menu.sorted_index = param.get('sorted_index')
        menu.icon = param.get('icon')
        menu.save()
        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_delete(self, param, session):
        mid = param.get('id')
        if not mid:
            return self.need_param('id')
        MenuInfo.delete_by_id(mid)
        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_clone(self, param, session):
        mid = param.get('id')
        if not mid:
            return self.need_param('id')
        menu = MenuInfo.get_by_id(mid)
        new_menu = MenuInfo()
        new_menu.menu = menu.menu
        new_menu.icon = menu.icon
        new_menu.url = menu.url
        new_menu.sorted_index = menu.sorted_index
        new_menu.save()
        return self.resp(1, http_result.RESULT_SUCCESS)
